const http = require("http");
const { Server } = require("socket.io");

const server = http.createServer();
const io = new Server(server, {
  cors: {
    origin: "http://localhost:9528", // 允许的客户端地址
    methods: ["GET", "POST"], // 允许的HTTP方法
    allowedHeaders: ["my-custom-header"], // 允许的自定义头
    credentials: true, // 允许携带凭证（如cookies）
  },
});

server.listen(8088, () => {
  console.log("服务器运行在 8088 端口");
});

// 监听客户端连接
io.on("connection", (socket) => {
  console.log("新用户连接:", socket.id);
  socket.emit('message', { content: 'Hello from server!' });
  setInterval(() => {
    // 发送欢迎消息
    socket.emit('message', { content: 'Hello from server!' });
  }, 15000);

  // 接收客户端消息
  socket.on("message", (data) => {
    console.log("收到消息:", data);
  });

  // 处理断开连接
  socket.on("disconnect", () => {
    console.log("用户断开连接:", socket.id);
  });
});


